package com.yourenbang.lingyun.transaction.web.service.impl.pay.transaction;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.pay.PayTypeEnum;
import com.yourenbang.lingyun.constants.enums.table.PayTransactionEnum;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.core.util.date.DateFormat;
import com.yourenbang.lingyun.domain.Merchant21;
import com.yourenbang.lingyun.domain.Merchant21Example;
import com.yourenbang.lingyun.mapper.Merchant21Mapper;
import com.yourenbang.lingyun.transaction.constant.LklTransTypeEnum;
import com.yourenbang.lingyun.transaction.job.model.dto.HsmpTransactionQueryResult;
import com.yourenbang.lingyun.transaction.web.service.PayTransactionFormatService;
import com.yourenbang.merchant.api.service.yxy.MerchantYxyApiService;
import com.yourenbang.transaction.api.model.vo.pay.PayTransaction;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

@Service("hsmpTransactionFormatService")
@Slf4j
public class HsmpTransactionFormatServiceImpl implements PayTransactionFormatService {
    @Autowired
    MerchantYxyApiService merchantYxyApiService;
    @Resource
    Merchant21Mapper merchant21Mapper;

    @Override
    public PayTransaction payTransactionFormat(JSONObject dto) {
        Merchant21Example merchant21Example = new Merchant21Example();
        merchant21Example.createCriteria().andThirdMerchantIdEqualTo(dto.getIntValue("shopId")).andChannelIdEqualTo(ChannelIdEnums.LDHS_MAPAI.getCode());
        List<Merchant21> merchant21List = merchant21Mapper.selectByExample(merchant21Example);
        if (CollectionUtils.isEmpty(merchant21List)) {
            KLog.info("慧商码牌商户获取为空，{}", dto.toJSONString());
            return null;
        }
        if (!HsmpTransactionQueryResult.ORDER_STATUS_2.equals(dto.getInteger("orderStatus"))) {
            KLog.info("交易状态非支付成功，跳过，{}", dto.toJSONString());
            return null;
        }
        Merchant21 merchant21 = merchant21List.get(0);
        PayTransaction payTransaction = new PayTransaction();
        payTransaction.setUserBaseId(merchant21.getUserBaseId());
        payTransaction.setMerchantId(merchant21.getMerchantId());
        payTransaction.setMerchantNo(merchant21.getMerchantNo());
        payTransaction.setMerchantName(merchant21.getMerchantName());
        payTransaction.setPhone(merchant21.getPhone());
        payTransaction.setRealName(merchant21.getRealName());
        payTransaction.setOrderNo(dto.getString("orderCode"));
        payTransaction.setTransactionNo(dto.getString("orderCode"));
        payTransaction.setTransactionAmount(dto.getBigDecimal("orderAmount"));
        payTransaction.setRate(merchant21.getRateCredit());
        BigDecimal transactionFee = dto.getBigDecimal("orderAmount").subtract(dto.getBigDecimal("orderAmountShould"));
        payTransaction.setTransactionFee(transactionFee.compareTo(BigDecimal.ZERO)>=0 ? transactionFee : BigDecimal.ZERO);
        payTransaction.setCardFlag(formatCardFlag(dto.getString("payMode")));
        payTransaction.setTransactionCardType(payTransaction.getCardFlag());
        payTransaction.setStatus(PayTransactionEnum.TransactionStatus.STATUS_10.getCode());
        payTransaction.setTransactionTime(DateFormat.DATETIME_DEFAULT.parse(dto.getString("createTime")));
        payTransaction.setTransactionMonth(StringUtils.left(dto.getString("createTime"), 7).replace("-", ""));
        payTransaction.setTransactionDay(StringUtils.left(dto.getString("createTime"), 10).replace("-", ""));
        payTransaction.setFrontSuccessTime(payTransaction.getTransactionTime());
        payTransaction.setFeeAmt(BigDecimal.ZERO);
        payTransaction.setAccAmt(dto.getBigDecimal("orderAmount"));
        payTransaction.setChannelId(merchant21.getChannelId());
        payTransaction.setPlatNo(merchant21.getPlatNo());
        payTransaction.setIsDel(false);
        payTransaction.setTransType(LklTransTypeEnum.TYPE_012002.getTransType());
        payTransaction.setProfitFlag(checkIsProfitFlag(payTransaction));
        return payTransaction;
    }

    @Override
    public JSONObject dyUrlRequest(String uri, Map<String, Object> bodyJson) {
        return null;
    }

    @Override
    public JSONObject dyUrlRequestByPayType(String uri, Map<String, Object> bodyJson, PayTypeEnum payTypeEnum) {
        return null;
    }

    /**
     * 格式化卡类型
     * 支付方式(0:微信 , 1支付宝 ,2现金 , 3免单, 4会员账户,5抹零)
     *
     * @param payMode 支付方式
     * @return 银小云卡类型
     */
    private String formatCardFlag(String payMode) {
        if ("0".equals(payMode)) {
            return PayTransactionEnum.CardFlagEnum.WECHAT.getCode();
        } else if ("1".equals(payMode)) {
            return PayTransactionEnum.CardFlagEnum.ALIPAY.getCode();
        } else {
            return payMode;
        }
    }

    /**
     * 判断是否计入分润
     */
    private boolean checkIsProfitFlag(PayTransaction payTransaction) {
        //贷记卡且非押金交易才计入分润
        return StringUtils.equalsAny(payTransaction.getCardFlag(),
                PayTransactionEnum.CardFlagEnum.ALIPAY.getCode(),
                PayTransactionEnum.CardFlagEnum.WECHAT.getCode(),
                PayTransactionEnum.CardFlagEnum.CREDIT_CARD.getCode(),
                PayTransactionEnum.CardFlagEnum.UNIONCODE.getCode()) &&
                payTransaction.getAccAmt().compareTo(BigDecimal.ZERO) > 0;
    }
}
